package se.energimyndigheten.lampguiden.bulbreplacement;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;

import se.energimyndigheten.lampguiden.HasInfoPage;
import se.energimyndigheten.lampguiden.LightSource;
import se.energimyndigheten.lampguiden.MainActivity;
import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.SwappableFragment;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

public class SocketGridFragment extends SwappableFragment implements HasInfoPage {

    public static final String KEY_SOCKET = "SOCKET";

    private static final String INFO_PATH = "Help/sv_Socket.html";
    private static final String TAG = SocketGridFragment.class.getSimpleName();

    private final String[] SocketExceptions = new String[] {"Halogen_stift", "LED", "Halogen_stift", "Lagenergi", "Lysror"};

    private ArrayList<GalleryItem> mList;
    private LightSource[] mLights = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setRetainInstance(true);
        setHasOptionsMenu(true);
        loadLightSources();
        return inflater.inflate(R.layout.socket_grid, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        addFragmentSwapper(getActivity());

        // show list of light sources as grid view
        GridView gridView = (GridView) view.findViewById(R.id.grid_view);
        gridView.setAdapter(new CardGridAdapter(getActivity(), mList.toArray(new GalleryItem[mList.size()])));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                onGridItemClick(position);
            }
        });
        setTitle(R.string.section_socket_hint);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.actionbar_info, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     * Load light sources from json
     */
    private void loadLightSources() {
        mList = new ArrayList<>();
        String json;

        // get lights from json
        try {
            json = AssetsUtil.getFileContents(getActivity().getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE);
            mLights = AssetsUtil.getLightSourcesFromJson(json);
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

        // create gallery from lights
        for (LightSource light : mLights) {
            mList.add(new GalleryItem(light.getImages()[LightSource.IMAGE_BASE], light.getCaption()));
        }
    }

    @Override
    public String getInfoPageUrl() {
        return INFO_PATH;
    }

    @Override
    public String getInfoPageTitle() {
        return getResources().getString(R.string.section_socket_title);
    }

    class GalleryItem {
        int image;
        String info;

        public GalleryItem(int image, String info) {
            this.image = image;
            this.info = info;
        }
    }

    class GalleryItemViewHolder {
        ImageView mImage = null;
        TextView mText = null;

        GalleryItemViewHolder(View item) {
            mImage = (ImageView) item.findViewById(R.id.grid_item_image);
            mText = (TextView) item.findViewById(R.id.grid_item_text);
        }
    }

    class CardGridAdapter extends BaseAdapter {
        private Context mContext;
        private GalleryItem[] mItems;

        public CardGridAdapter(Context context, GalleryItem[] items) {
            mContext = context;
            mItems = items;
        }

        @Override
        public int getCount() {
            return mItems.length;
        }

        @Override
        public Object getItem(int position) {
            return mItems[position];
        }

        @Override
        public long getItemId(int position) {
            return mItems[position].image;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GalleryItemViewHolder holder;

            // recycle with holder pattern to increase performance
            // performance is still poor on low end devices due to the use of large images
            if (convertView == null) {
                // inflate and create new holder
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.socket_grid_item, parent, false);
                holder = new GalleryItemViewHolder(convertView);
            } else {
                // grab holder from tag
                holder = (GalleryItemViewHolder) convertView.getTag();
            }
            if (holder == null) {
                holder = new GalleryItemViewHolder(convertView);
                convertView.setTag(holder);
            }

            holder.mImage.setImageResource(mItems[position].image);
            holder.mText.setText(mItems[position].info);
            return convertView;
        }
    }

    public void onGridItemClick(int position) {
        final int bounds = mLights.length - SocketExceptions.length;
        if (position < bounds) {
            Fragment powerFrag = new PowerFragment();
            Bundle args = new Bundle();
            args.putInt(KEY_SOCKET, position);
            powerFrag.setArguments(args);
            swapFragment(powerFrag, true);
        } else {
            String EXPLAIN_PATH = MainActivity.HTML_BASEPATH + ExplainFragment.HTML_PATH + SocketExceptions[position - bounds] + ".html";
            ExplainFragment eFrag = new ExplainFragment();
            Bundle args = new Bundle();
            args.putString(ExplainFragment.EXTRA_HTML_PATH, EXPLAIN_PATH);
            eFrag.setArguments(args);
            swapFragment(eFrag, true);
        }
    }
}
